package middleware

import (
	"net/http"

	"github.com/iriver/ai-offer/backend/internal/types"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// RoleAuthMiddleware 角色验证中间件
type RoleAuthMiddleware struct {
	allowedRoles []string
}

// NewRoleAuthMiddleware 创建新的角色验证中间件
func NewRoleAuthMiddleware(roles ...string) *RoleAuthMiddleware {
	return &RoleAuthMiddleware{
		allowedRoles: roles,
	}
}

// Handle 处理请求
func (m *RoleAuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 获取用户信息
		claims, err := GetUserInfo(r)
		if err != nil {
			logx.Errorf("获取用户信息失败: %v", err)
			httpx.WriteJson(w, http.StatusUnauthorized, types.NewErrorResponse(types.ErrUnauthorized, "未授权访问"))
			return
		}

		// 验证角色
		if !m.hasRole(claims.Role) {
			logx.Infof("用户权限不足: %s，需要角色: %v，当前角色: %s", claims.Email, m.allowedRoles, claims.Role)
			httpx.WriteJson(w, http.StatusForbidden, types.NewErrorResponse(types.ErrForbidden, "权限不足"))
			return
		}

		// 继续处理请求
		next(w, r)
	}
}

// 检查用户是否拥有所需角色
func (m *RoleAuthMiddleware) hasRole(userRole string) bool {
	if len(m.allowedRoles) == 0 {
		return true
	}

	for _, role := range m.allowedRoles {
		if userRole == role {
			return true
		}
	}

	return false
}
